package com.gycode.vpush.job.handler;

import com.alibaba.fastjson.JSONObject;
import com.gycode.vpush.utils.mq.ProducerUtil;
import com.gycode.vpush.constant.CommonConstant;
import com.gycode.vpush.dto.request.WebSocketSendUserDTO;
import com.gycode.vpush.mapper.SendMessageMapper;
import com.gycode.vpush.mapper.SendMessageUserMapper;
import com.gycode.vpush.vo.UnReadMessageVO;
import com.gycode.vpush.websocket.WebSocketServer;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author PC
 */
@Slf4j
@Component
@JobHandler("timingWebSocketHandler")
public class TimingWebSocketHandler  extends IJobHandler {

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private SendMessageMapper sendMessageMapper;

    @Autowired
    private SendMessageUserMapper sendMessageUserMapper;

    @Autowired
    private ProducerUtil producerUtil;


    @Override
    public ReturnT<String> execute(String s) throws Exception {
        UnReadMessageVO unReadMessageVO = new UnReadMessageVO();
        unReadMessageVO.setPointTime(new Date());
        List<WebSocketSendUserDTO> webSocketMsgDTOList =  sendMessageUserMapper.getUnReadMessageUserList(unReadMessageVO);
        log.info("获取定时推送的消息:{}",JSONObject.toJSONString(webSocketMsgDTOList));
        if (!CollectionUtils.isEmpty(webSocketMsgDTOList)){
            producerUtil.sendMsgBroadcast(CommonConstant.MQ_TAG_WEBSOCKET_TIMING_MSG,
                    JSONObject.toJSONBytes(webSocketMsgDTOList),
                    UUID.randomUUID().toString());
        }
        return ReturnT.SUCCESS;
    }
}
